package com.guanjia.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.guanjia.entity.*;
import com.guanjia.entity.vo.*;
import com.guanjia.mapper.*;
import com.guanjia.service.CrowdFundingService;
import com.guanjia.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * 用户个人中心
 */
@Controller
@RequestMapping("/userCenter")
public class UserCenterController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private InvestMapper investMapper;

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private CrowdFundingService crowdFundingService;

    @Autowired
    private CrowdDealMapper crowdDealMapper;

    @Autowired
    private RepaymentMapper repaymentMapper;

    @Autowired
    private CreditinfoMapper creditinfoMapper;

    @Autowired
    private BussinessMapper bussinessMapper;

    private User user2=null;
    private boolean flag = false;

    @RequestMapping("/index")
    public String intoUserIndex(Model model, HttpSession session){
        /*获取登录用户信息 s*/
        UserDetails userDetails=null;
        try {
            userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        catch (Exception e){
            return "0";
        }
        String username= userDetails.getUsername();
        User user = userMapper.findUserBytell(username);
        /*获取登录用户信息 e*/
        System.out.println(user);

        //创建个人信息数据 s
        UserInformation userInformation1 = userMapper.findUserInfoByUserId(user.getId());
        if(userInformation1== null){
            UserInformation userInformation =new UserInformation();
            userInformation.setUserId(user.getId());
            userInformation.setLoanlimit(20000);
            userMapper.insertUserInfo(userInformation);
        }
        //创建个人信息数据 e

        //创建企业信息数据 s
        EnterpriseInformation enterpriseInformation1 = userMapper.findUserEnterInfoByUserId(user.getId());
        if(enterpriseInformation1== null){
            EnterpriseInformation enterpriseInformation =new EnterpriseInformation();
            enterpriseInformation.setUserId(user.getId());
            userMapper.insertEnter(enterpriseInformation);
        }
        //创建企业信息数据 e

        if (flag == false){
            user.setLastlogintime(new Date());
            userMapper.updateById(user);
            flag=true;
        }



        model.addAttribute("user",user);
        session.setAttribute("user",user);
        user2=user;
        System.out.println(user2);
        List<InvestVo> list = investMapper.selectByUserId(user2.getId());
        System.out.println(list);
        Integer allInvestMoney = investMapper.sumBalanceByUserId(user2.getId());
        Integer MonthInvestBalance =investMapper.sumMonthBalanceByUserId(user2.getId());

        //总收益
        Double sumreturned = 0.0;
        for (int i=0;i<list.size();i++){
            if (((InvestVo)list.get(i)).getReturnedNum() !=null){
                double money=((InvestVo)list.get(i)).getInterest()*((InvestVo)list.get(i)).getReturnedNum();
                sumreturned +=money;
            }
        }
        model.addAttribute("sumreturned",sumreturned);
        model.addAttribute("investments",list);
        model.addAttribute("allInvestMoney",allInvestMoney);
        model.addAttribute("MonthInvestBalance",MonthInvestBalance);
        return "cfgj/user_index";
    }

    @ResponseBody
    @RequestMapping("/getEcharts")
    public  List<EchartsVo> getEcharts(){
        List<InvestVo> list = investMapper.selectByUserId(user2.getId());
        List<EchartsVo> echartsVos=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            EchartsVo echartsVo=new EchartsVo(list.get(i).getInvestmoney(),list.get(i).getProjectname());
            echartsVos.add(echartsVo);
        }


        return echartsVos;
    }



    /**
     * 退出
     */
    @RequestMapping("/logout")
    public String logout(){
        flag=false;

        return "cfgj/login";
    }
    /**
     *跳转至安全设置
     */
    @RequestMapping("/safe")
    public String safe(Model model){
        UserInformation userInformation = userMapper.findUserInfoByUserId(user2.getId());
//        System.out.println(user2);
//        System.out.println(userInformation);
        model.addAttribute("user",user2);
        model.addAttribute("userinfo",userInformation);
        return "cfgj/user_safe";
    }

    /**
     *跳转至账户设置
     */
    @RequestMapping("/account")
    public String account(Model model){
        UserInformation userInformation = userMapper.findUserInfoByUserId(user2.getId());
//        System.out.println(userInformation);
    /*    if(userInformation == null){
            userInformation.setIDcard("未实名认证");
            userInformation.setName("未实名认证");
        }*/
        if (userInformation.getStatus() != 2){
            userInformation.setIDcard("未实名认证");
            userInformation.setName("未实名认证");
        }

        model.addAttribute("userinfo",userInformation);
        model.addAttribute("user",user2);
        return "cfgj/user_account";
    }

    /**
     * 保存个人信息表单
     */
    @RequestMapping("/save")
    public String accountSave(UserInformationVo userInformationVo){
        UserInformation userInformation = userMapper.findUserInfoByUserId(user2.getId());
        userInformation.setSex(userInformationVo.getSex());
        userInformation.setAge(userInformationVo.getAge());
        userInformation.setEducational(userInformationVo.getEducational());
        userInformation.setSchool(userInformationVo.getSchool());
        userInformation.setCompany(userInformationVo.getCompany());
        userInformation.setSalary(userInformationVo.getSalary());
        userInformation.setNowaddress(userInformationVo.getNowaddress());

//        System.out.println(userInformation);
        //userInformation.setUserId(user2.getId());
        userMapper.updateUserInfo(userInformation);
        return "redirect:account";
    }

    /**
     * 保存个人信息表单
     */
    @RequestMapping("/saveIDcard")
    public String saveIDcard(String name,String IDcard){

        UserInformation userInformation = userMapper.findUserInfoByUserId(user2.getId());
        userInformation.setIDcard(IDcard);
        userInformation.setName(name);
        userInformation.setStatus(1);

//        System.out.println(userInformation);
        //userInformation.setUserId(user2.getId());
        userMapper.updateUserInfo(userInformation);
        return "redirect:safe";
    }


    /**
     *跳转至公司账户设置
     */
    @RequestMapping("/company")
    public String company(Model model){
        EnterpriseInformation enterpriseInformation = userMapper.findUserEnterInfoByUserId(user2.getId());
//        System.out.println(enterpriseInformation);
        model.addAttribute("user",user2);
        model.addAttribute("enterpriseInformation",enterpriseInformation);
        return "cfgj/company_account";
    }

    /**
     * 保存公司信息
     */
    @RequestMapping("savecompany")
    public String savecompany(EnterpriseInformation enterpriseInformation){
        userService.updateenterInfo(enterpriseInformation);
            //userMapper.updateenterInfo(enterpriseInformation);
       return "redirect:company";
    }

    /**
     * 异步获取账户信息
     */
    @RequestMapping("/ajaxaccount")
    public UserInformation ajaxaccount(){
        UserInformation userInformation = userMapper.findUserInfoByUserId(user2.getId());
        return userInformation;
    }

    /**
     *跳转至借贷设置
     */
    @RequestMapping("/loan")
    public String loan(Model model){
        List<CreditInformationVo> list = borrowMapper.selectListByUserId(user2.getId());
        Integer allLoanMoney = borrowMapper.sumBalanceByUserId(user2.getId());
        Integer MonthBalance =borrowMapper.sumMonthBalanceByUserId(user2.getId());
        System.out.println(list);
        //总还款
        Double sumreturned = 0.0;
        for (int i=0;i<list.size();i++){
            if (((CreditInformationVo)list.get(i)).getProjectreturned() !=null){
                double money=((CreditInformationVo)list.get(i)).getProjectreturned();
                sumreturned +=money;
            }
        }
        //已还款期数
        //Integer returnedNum = repaymentMapper.selectCountByCreditid()
//        System.out.println(allLoanMoney);
//        System.out.println(list);
        model.addAttribute("user",user2);
        model.addAttribute("loans",list);
        model.addAttribute("allLoanMoney",allLoanMoney);
        model.addAttribute("MonthBalance",MonthBalance);
        model.addAttribute("sumreturned",sumreturned);
        return "cfgj/user_jd";
    }

    @ResponseBody
    @RequestMapping("/getEchartsLoan")
    public  List<EchartsVo> getEchartsLoan(){
        List<CreditInformationVo> list = borrowMapper.selectListByUserId(user2.getId());
        List<EchartsVo> echartsVos=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            EchartsVo echartsVo=new EchartsVo(Double.valueOf(list.get(i).getBorrowmoney()),list.get(i).getProjectabstract());
            echartsVos.add(echartsVo);
        }


        return echartsVos;
    }
    /**
     *跳转至众筹设置
     */
    @RequestMapping("/Crowd")
    public String Crowd(Model model){
        System.out.println(user2.getId());
        List<CrowdFunding> crowdFunding = crowdFundingService.findCrowdFundingListById(user2.getId());
        List<CrowdFundingVo> crowdDeals = crowdDealMapper.selectListByUserId(user2.getId());
       System.out.println(crowdDeals);
        System.out.println(crowdFunding);
        model.addAttribute("joincrowdFunding",crowdDeals);
        model.addAttribute("crowdFunding",crowdFunding);
        model.addAttribute("user",user2);
        return "cfgj/user_zc";
    }

    /**
     *跳转至交易记录
     */
    @RequestMapping("/transaction")
    public String transaction(Model model,Integer page,Integer size,String group, String start, String end){
       /*List<Bussiness> list = userService.findUsertransactionByUserId(user2.getId());*/


        String  allrechange = userMapper.SumrechangetransactionByUserId(user2.getId());
        String allforward =  userMapper.SumtforwardransactionByUserId(user2.getId());

        if (allrechange== null) model.addAttribute("allrechange","0.0");
        else model.addAttribute("allrechange",allrechange);

        if (allforward== null) model.addAttribute("allforward","0.0");
        else model.addAttribute("allforward",allforward);
        Map<String,Object> map = new HashMap<>();
        BussinessVo bussinessVo = new BussinessVo();
        bussinessVo.setId(user2.getId());
        bussinessVo.setSubgroup(group);
        bussinessVo.setStart(start);
        bussinessVo.setEnd(end);
        System.out.println(bussinessVo);
        if(group==null){
            group="";
        }
        IPage<Bussiness> ipage=userService.findPageList(page,size,group,start,end,user2.getId());
        model.addAttribute("transaction",ipage.getRecords());
        model.addAttribute("count",ipage.getTotal());
        model.addAttribute("curr",page);
        model.addAttribute("user",user2);
        model.addAttribute("group",group);
        model.addAttribute("start",start);
        model.addAttribute("end",end);
        return "cfgj/user_transaction";
    }

    @RequestMapping("/getData")
    @ResponseBody
    public Map<String,Object> getData(String group,String start, String end){
        Map<String,Object> map = new HashMap<>();
        BussinessVo bussinessVo = new BussinessVo();
        bussinessVo.setId(user2.getId());
        bussinessVo.setSubgroup(group);
        bussinessVo.setStart(start);
        bussinessVo.setEnd(end);
        System.out.println(bussinessVo);
        List<Bussiness> list = userService.findUsertransactionInfoByUserId(bussinessVo);
        map.put("list",list);
        return map;
    }

   /*
        异步刷新搜索数据
    */
   @RequestMapping("/transactioninfo")
   @ResponseBody
   public Map<String,Object> transactioninfo(String group, String start, String end, Integer pageIndex, Integer pageSize){
      /* BussinessVo bussinessVo = new BussinessVo();
       bussinessVo.setId(user2.getId());
       bussinessVo.setSubgroup(group);
       bussinessVo.setStart(start);
       bussinessVo.setEnd(end);
       System.out.println(bussinessVo);
       List<Bussiness> list = userService.findUsertransactionInfoByUserId(bussinessVo);
       *//*if ((bu != null||group=="") &&(start != null|| start =="") &&(end != null ||end == "")){
           return list;
       }else{
           List<Bussiness> list = userService.findUsertransactionByUserId(user2.getId());
           return list;
       }*//*
       return list;*/
       Map<String,Object> map = new HashMap<>();
       /*IPage<Bussiness> pageList = userService.findPageList(pageIndex,pageSize,group,start,end);
       map.put("data",pageList.getRecords());
       map.put("count",pageList.getTotal());*/
       return map;
   }











     /*
     * *更新user跳转借贷(同步）
     *//*
    @RequestMapping("/updateUser")
    public String updateUser(Model model,Integer balance){
        User user = new User();
        user.setId(user2.getId());
        user.setBalance(user2.getBalance()-balance);
        userMapper.updateById(user);
        user2=userMapper.findUserBytell(user2.getTell());

        List<CreditInformation> list = borrowMapper.selectListByUserId(user2.getId());
        Integer allLoanMoney = borrowMapper.sumBalanceByUserId(user2.getId());
        Integer MonthBalance =borrowMapper.sumMonthBalanceByUserId(user2.getId());

        System.out.println(allLoanMoney);
        System.out.println(list);
        model.addAttribute("user",user2);
        model.addAttribute("loans",list);
        model.addAttribute("allLoanMoney",allLoanMoney);
        model.addAttribute("MonthBalance",MonthBalance);
        return "cfgj/user_jd";
    }*/

    //两个Double数相加
    public static Double add(Double v1,Double v2){

        BigDecimal b1 = new BigDecimal(v1.toString());

        BigDecimal b2 = new BigDecimal(v2.toString());

        return b1.add(b2).doubleValue();

    }
    //两个Double数相加
    public static Double sub(Double v1,Double v2){

        BigDecimal b1 = new BigDecimal(v1.toString());

        BigDecimal b2 = new BigDecimal(v2.toString());

        return  b1.subtract(b2).doubleValue();

    }

    /**
     *更新user金额(异步）
     */
    @RequestMapping("/DecUserMoney")
    @ResponseBody
    public User DecUserMoney(String balance,Integer id){
        //更新还款
        double balan = Double.valueOf(balance);

        Bussiness bussiness = new Bussiness();
        bussiness.setCreatetime(new Date());
        bussiness.setType("3");
        bussiness.setUserId(user2.getId());
        bussiness.setBalancein(0.0);
        bussiness.setBalanceout(balan);

        bussiness.setBalance(sub(user2.getBalance(),balan));

        bussinessMapper.insertBussiness(bussiness);
       //找到多少个人投资了
        List<InvestInfoVo> vo=investMapper.findById(id);
        Bussiness bussiness1 = new Bussiness();
        for (int i =0;i  <vo.size();i++){
            User user1 = userMapper.findUserById(vo.get(i).getId());
            user1.setBalance(user1.getBalance()+vo.get(i).getInterest());
            userMapper.updateById(user1);

            bussiness1.setCreatetime(new Date());
            bussiness1.setType("2");
            bussiness1.setUserId(user1.getId());
            bussiness1.setBalancein(vo.get(i).getInterest());
            bussiness1.setBalanceout(0.0);
            bussiness1.setBalance(add(user1.getBalance(),balan));
            bussinessMapper.insertBussiness(bussiness1);
        }

        //更新金额

        User user = new User();
        user.setId(user2.getId());
        user.setBalance(sub(user2.getBalance(),balan));
        userMapper.updateById(user);
        user2=userMapper.findUserBytell(user2.getTell());

        Integer flag =  repaymentMapper.updateByCreditid(id);
        if (flag == 0){
            CreditInformation creditInformation=creditinfoMapper.findCreditInfoById(id);
            creditInformation.setStep("3");
            creditinfoMapper.updateById(creditInformation);

        }

       return user2;
    }

    /**
     *更新user跳转借贷(异步）
     */
    @RequestMapping("/addUserMoney")
    @ResponseBody
    public User addUserMoney(Integer balance){
        User user = new User();
        user.setId(user2.getId());
        user.setBalance(user2.getBalance()+balance);
        userMapper.updateById(user);
        user2=userMapper.findUserBytell(user2.getTell());

        return user2;
    }

    /**
     * 修改密码
     */
    @RequestMapping("/modifyPwd")
    public String modifyPwd(User user,Model model) {
        model.addAttribute("user",user2);
        return "cfgj/modifyUserPwd";
    }

    /**
     * 更新密码
     */
    @RequestMapping("/modifyPwdSubmit")
    @ResponseBody
    public String modifyPwdSubmit(User user) {
        userService.updataPwd(user);
        return "success";
    }

    /**
     * 修改手机
     */
    @RequestMapping("/modifymobel")
    public String modifymobel(User user,Model model) {
        model.addAttribute("user",user2);
        return "cfgj/modifyUserTell";
    }

    /**
     * 更新手机
     */
    @RequestMapping("/modifymobelSubmit")
    @ResponseBody
    public String modifymobelSubmit(User user) {
//        System.out.println(user);
        userService.updataTell(user);
        return "success";
    }

    /**
     * 充值
     */
    @RequestMapping("/recharge")
    public String rechargemoney(User user,Model model) {
        model.addAttribute("user",user2);
        return "cfgj/rechargemoney";
    }

    /**
     * 充值成功
     */
    @RequestMapping("/rechargeSubmit")
    @ResponseBody
    public String rechargemoneySubmit(User user,HttpSession session) {
//        System.out.println("rechargeSubmit");
//        System.out.println(user);
        double  money = user.getBalance();
        user.setBalance(user.getBalance()+user2.getBalance());
        userService.updatamoney(user);
        user2=userMapper.findUserById(user.getId());
        Bussiness bussiness = new Bussiness();
        bussiness.setType("0");
        bussiness.setBalancein(money);
        bussiness.setBalanceout(0.0);
        bussiness.setCreatetime(new Date());
        bussiness.setUserId(user.getId());
        bussiness.setBalance(user2.getBalance());
        userMapper.insertBussiness(bussiness);
//        System.out.println(user2);
        session.setAttribute("user",user2);
        return "success";
    }

    /**
     * 提现
     */
    @RequestMapping("/forward")
    public String forward(Model model) {
        model.addAttribute("user",user2);
        return "cfgj/forward";
    }

    /**
     * 提现成功
     */
    @RequestMapping("/forwardSubmit")
    @ResponseBody
    public String forwardSubmit(User user,HttpSession session) {
        System.out.println("rechargeSubmit");
        System.out.println(user);
        double  money = user.getBalance();
        user.setBalance(user2.getBalance()-user.getBalance());
        userService.updatamoney(user);
        user2=userMapper.findUserById(user.getId());
        Bussiness bussiness = new Bussiness();
        bussiness.setType("1");
        bussiness.setBalancein(0.0);
        bussiness.setBalanceout(money);
        bussiness.setCreatetime(new Date());
        bussiness.setUserId(user.getId());
        bussiness.setBalance(user2.getBalance());
        userMapper.insertBussiness(bussiness);
//        System.out.println(user2);
        session.setAttribute("user",user2);
        return "success";
    }

}
